/**
 * Created by huangzx on 2015/6/16.
 */
define('framework/tab/GillionTabModule', [
    'angular'
], function(angular) {

    //滚动条按钮显示判断
    function setScrollers($panel) {
        var headerWidth = $panel.find('.tab-items').width(),
            navWidth = 0;
        $panel.find('.tab-items').children().each(function(){
            navWidth += $(this).outerWidth(true);
        });
        if (navWidth > headerWidth){
            $panel.find('.tab-nav > .btn').show();
        } else {
            $panel.find('.tab-nav > .btn').hide();
        }
    }

    /**
     * 页前面板控制器
     * @param selector
     * @param options
     * @constructor
     */
    function TabPanel(element, options) {
        this.options = options || {};
        this.$panel = element;
        this.$navs = element.find('.tab-items');
        this.$tabs = element.find('.tab-body');
        this.navs = {};
        this.tabs = {};
        this.bindEvents();
    }

    /**
     * 事件绑定
     */
    TabPanel.prototype.bindEvents = function(){
        var self = this,
            $panel = self.$panel,
            $navs = self.$navs,
            options = self.options;
        $navs.on('click', '.fi-refresh-small', function(){
            var $nav = angular.element(this).parent().parent('li');
            self.loadTab($nav.data('title')+'_'+$nav.data('url'));
            return false;
        }).on('click', '.fi-close-small', function(){ //阻止事件冒泡
            var $nav = angular.element(this).parent().parent('li');
            if (angular.isFunction(options.onBeforeClose) &&
                options.onBeforeClose($nav.data('title'), $nav.data('url')) === false) {
                return false;
            }
            self.closeTab($nav.data('title')+'_'+$nav.data('url'));
            angular.isFunction(options.onClose) && options.onClose($nav.data('title'), $nav.data('url'));
            return false;
        }).on('click', 'a', function(){
            var $currNav = angular.element(this).parent('li');
            if (angular.isFunction(options.onBeforeSelect) &&
                options.onBeforeSelect($currNav.data('title'), $currNav.data('url')) === false) {
                return;
            }
            self.selectTab($currNav.data('title')+'_'+$currNav.data('url'));
            angular.isFunction(options.onSelect) && options.onSelect($currNav.data('title'), $currNav.data('url'));
        });
    };

    /**
     * 添加标签页
     * @param options
     */
    TabPanel.prototype.addTab = function(options) {
        options = options || {};
        var self = this,
            fixModal = self.options.fixModal,
            async = self.options.async,
            $panel = self.$panel,
            $navs = self.$navs,
            $tabs = self.$tabs,
            navs = self.navs,
            tabs = self.tabs,
            title = options.title,
            url = options.url,
            active = options.active,
            key = title + '_' + url, //定义每个页签key的唯一性
            html = options.html,
            nav, tab = options.tab;

        //最多打开tab数量、重复的tab不添加
        if ($navs.children().size() == self.options.tabNum ||
            (navs[key] && tabs[key])) {
            tab && tab.remove();
            return;
        }

        if (fixModal) {    //固定标签页
            nav = angular.element('<li><a>' + title + '</a></li>');
        } else {        //带刷新和关闭按钮
            nav = angular.element('<li><a>' + title+ '</a><a class="btn"><i class="fi fi-close-small"></i></a></li>');
            url && nav.prepend('<a class="btn"><i class="fi fi-refresh-small"></i></a>');
        }
        $navs.append(nav.data('title', title).data('url', url));
        navs[key] = nav;

        tab = tab || angular.element('<div></div>');
        tab = url?tab.addClass('tab-body-iframe'):tab.addClass('tab-body-html');
        $tabs.append(tab.data('title', title).data('url', url));
        tabs[key] = tab;
        if(!async) self.loadTab(key);
        active && self.selectTab(key);
        setScrollers(self.$panel);
    };

    /**
     * 选中标签页
     * @param key
     */
    TabPanel.prototype.selectTab = function(key){
        var self = this,
            nav, tab;
        if (typeof key === 'number'){
            nav = self.$navs.children().eq(key);
            key = nav.data('title') + '_' + nav.data('url');
        } else {
            nav = self.navs[key];
        }
        tab = self.tabs[key];

        nav && nav.attr('active', 'true').siblings().removeAttr('active');
        //存在url的时候只load一次页面
        if (!tab.data('load')) {
            self.loadTab(key);
        }
        tab && tab.attr('active', 'true').siblings().removeAttr('active');
    };

    /**
     * 加载某个页面，以iframe形式展示
     * @param key
     */
    TabPanel.prototype.loadTab = function(key) {
        var tab = this.tabs[key];
        if (tab.data('url')) {
            tab.html('<iframe frameborder="0" src="' + tab.data('url') + '"></iframe>');
            tab.data('load', true);
        }
    };

    /**
     * 关闭标签页
     * @param key
     */
    TabPanel.prototype.closeTab = function(key) {
        var self = this,
            nav = self.navs[key],
            tab = self.tabs[key],
            selectNav = nav && nav.next();  //关闭后新的标签导航
        if (!selectNav.html()) selectNav = nav.prev();
        if (nav.attr('active') && selectNav.html()) {
            self.selectTab(selectNav.data('title')+'_'+selectNav.data('url'));
        }
        nav.remove(); tab.remove();
        delete this.navs[key];
        delete this.tabs[key];
        setScrollers(this.$panel);
    };

    return angular.module('GillionTabModule', []).
        directive('gTabPanel', function() {
            return {
                restrict: 'E',
                scope:{
                    fixModal:'@',
                    tabNum:'@',
                    async:'@',

                    api: "=",
                    initCallback: '=',

                    onBeforeSelect:'=',
                    onSelect:'=',
                    onBeforeClose: '=',
                    onClose:'='
                },
                transclude: true,
                require: '?gTabPanel',
                replace:true,
                template: '<div class="tab">\n    <div class="tab-nav">\n        <a class="btn" rel="prev" ng-click="scrollLeft()"><i class="fi fi-arrow-left"></i></a>\n        <div class="tab-bar"><ul class="tab-items"></ul></div>\n        <a class="btn" rel="next" ng-click="scrollRight()"><i class="fi fi-arrow-right"></i></a>\n    </div>\n    <div class="tab-body" ng-transclude></div>\n</div>',
                controller:function($scope, $element, $attrs) {
                    var fixModal = true, //页签模式
                        async = true,
                        tabNum = parseInt($scope.tabNum) || 999,     //最多打开页签数
                        options;
                    if($scope.fixModal === 'false') {
                        fixModal = false;
                        $element.attr('mode', 'dynamic')
                    }
                    if($scope.async === 'false') async = false;
                    options = {
                        fixModal: fixModal,
                        async: async,
                        tabNum: tabNum,
                        onBeforeSelect: $scope.onBeforeSelect,
                        onSelect: $scope.onSelect,
                        onBeforeClose: $scope.onBeforeClose,
                        onClose: $scope.onClose
                    };
                    this.tabPanel = new TabPanel($element, options);
                    // 开发接口给外面调用
                    if ($attrs.hasOwnProperty('api')) {
                        $scope.api = this.tabPanel;
                    }
                },
                link: function(scope, iEle, iAttrs, gTabPanelCtrl) {
                    scope.scrollLeft = function(){
                        var itemsDom  =  iEle.find('.tab-items')[0];
                        itemsDom.scrollLeft -= 50;
                    };
                    scope.scrollRight = function(){
                        var itemsDom  = iEle.find('.tab-items')[0];
                        itemsDom.scrollLeft += 50;
                    };
                    if (angular.isFunction(scope.initCallback)) {
                        scope.initCallback(gTabPanelCtrl.tabPanel);
                    }
                    angular.element(window).resize(function(){setScrollers(iEle);});
                }
            };
        }).
        directive('gTab', function(){
            return {
                restrict: 'E',
                replace:true,
                transclude: true,
                require:'^gTabPanel',
                template: '<div ng-transclude></div>',
                link: function(scope, iEle, iAttrs, gTabPanelCtrl) {
                    var opt = {
                        title: iAttrs.title || '新建标签页',
                        url: iAttrs.url,
                        tab: iEle,
                        active: iAttrs.active === 'true'
                    };
                    gTabPanelCtrl.tabPanel.addTab(opt);
                }
            };
        });
});